<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/15
 * Time: 10:34
 */

namespace app\api\controller;
use think\Cache;
use think\Db;
use app\wap\controller\Notify as Msg;
use app\admin\controller\Order;
use think\Exception;
use think\log;
use app\api\controller\KbxOrder as KbxOrder;
use think\Request;

error_reporting(E_ERROR);

class Viator
{
    public function _initialize()
    {
        Log::init([
            'type'  =>  'File',
            'path'  =>  APP_PATH.'logs/'
        ]);
    }

    private  $url='http://prelive.viatorapi.viator.com';//测试
    private  $apiKey='551894604619479248';
    private  $apiKey_ch='727282829547276699';//中文key
    private  $currencyCode='USD'; //货币方式
    //新版本的viator接口key 使用header添加参数 exp-api-key:xxx 发送请求
    //测试
    private $viator_exp_key = 'a1864811-d734-442f-bbb3-f19bdaf21a9d';
    //生产
//    private $viator_exp_key = 'f6e09b74-296b-48e1-ac20-59b9fcf000ff';
    private $zh_header = 'Accept-Language: zh';
    private $en_header = 'Accept-Language: en';
    public $statusArr = array(
        '1' => array(
            'orderStatus' => 'pending',
            'paymentStatus' => 'pending',
        ),
        '2' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'paid',
        ),
        '3' => array(
            'orderStatus' => 'finished',
            'paymentStatus' => 'paid',
        ),
        '4' => array(
            'orderStatus' => 'reviewed',
            'paymentStatus' => 'paid',
        ),
        '5' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'refunding',
        ),
        '6' => array(
            'orderStatus' => 'canceled',
            'paymentStatus' => 'refunding',
        ),
        '7' => array(
            'orderStatus' => 'expired',
            'paymentStatus' => 'pending',
        ),
        '8' => array(
            'orderStatus' => 'canceled',
            'paymentStatus' => 'refunded',
        ),
        '9' => array(
            'orderStatus' => 'toBeStarting',
            'paymentStatus' => 'rejected',
        ),
        '10' => array(
            'orderStatus' => 'unknown',
            'paymentStatus' => 'pending',
        )
    );

    public function index(){
        return '访问成功';
    }

    public function writeLog($msg,$fileName=''){//记录日志   by Suley
        if(!$msg) return false;
        $dir = '/var/www/html/log';
        $default_ext = '_test_'.date('Ymd');
        $fileName = !empty($fileName)?$fileName:$default_ext;
        $log = 'viator_log'.$fileName;
        //判断文件是否存在
        if(file_exists($dir.'/'.$log)){
            $filesize = filesize($dir.'/'.$log);
            if($filesize>3145728){//设置log文件大小为3mb
                rename($dir.'/'.$log,$dir.'/'.$log."".date('YmdH',time()));
            }
        }

        $result = file_put_contents($dir.'/'.$log,(date('Y-m-d H:i:s',time())).'   '.$msg."\r\n",FILE_APPEND);
        return $result;
    }

    /*
     * 组装函数
     * get_curl get请求
     * post_curl post 请求
     * object_array 对象转数组
     */
    public function get_curl($url,$header = []){
        $ch = curl_init();
        $header[]  = 'exp-api-key: '.$this->viator_exp_key;
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(!empty($header)){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_HEADER, 0);//返回response头部信息
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);
        $data =json_decode($output,true);

        return $data;
    }

    public function post_curl($url,$post_data,$header=''){

        $header[]  = 'exp-api-key: '.$this->viator_exp_key;
        $header[]  = 'Content-Type: application/json';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //设置为POST
        curl_setopt($ch, CURLOPT_POST, 1);
        //把POST的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        if($header){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_HEADER, 0);//返回response头部信息
        }
        $output = curl_exec($ch);
        curl_close($ch);
        $output=json_decode($output);
        return $output;
    }

    public function put_curl($url,$data,$header,$method='put'){
        $header[]  = 'exp-api-key: '.$this->viator_exp_key;
        $header[]  = 'X-HTTP-Method-Override: '. $method;

        $ch = curl_init(); //初始化CURL句柄
        curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
        curl_setopt($ch, CURLOPT_HEADER, $header);

        if($header){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_HEADER, 0);//返回response头部信息
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
        $document = curl_exec($ch);//执行预定义的CURL
        if(!curl_errno($ch)){
            $info = curl_getinfo($ch);
            echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
        } else {
            echo 'Curl error: ' . curl_error($ch);
        }
        curl_close($ch);

        return $document;
    }

    function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }

    /*
     * 城市表
     * /service/taxonomy/destinations
     */
    public function city(){
        $url = $this->url.'/service/taxonomy/destinations';
        $data = $this->get_curl($url);
        $list = [];
        foreach ($data['data'] as $a){
            $arr=[];
            $arr['id']  = $a['destinationId'];
            $arr['pid'] = $a['parentId'];
            $arr['ename']   = $a['destinationName'];
            $arr['type']    = $a['destinationType'];
            $list[] = $arr;
        }
//        需要时插入数据
        //$res = Db::name('dclcity')->insertAll($list);
        dump($list);
    }

    /*
     * 分类：
     * /service/taxonomy/categories
     *  dcategories 表
     */
    public function getCategories(){
        $res = Db::name('city')->where('destid','<>','')
//            ->where('destid','298')
            ->field('destid')->select();
        $arr=[];
        foreach ($res as $a){
            $url=$this->url.'/service/taxonomy/categories?destId='.$a['destid'];
            $data=$this->get_curl($url);
            $data=$this->object_array($data);
            if(empty($data['data'])){
                continue;
            }
            foreach ($data['data'] as $i){
                $list=[];
                $list['fid']=$i['id'];
                $list['pid']=0;
                $list['name']=$i['groupName'];
                $list['count']=$i['productCount'];
                $list['city']=$a['destid'];
                $arr[]=$list;
                if (count($i['subcategories'])>0){
                    foreach ($i['subcategories'] as $k){
                        $list=[];
                        $list['fid']=$k['subcategoryId'];
                        $list['pid']=$k['categoryId'];
                        $list['name']=$k['subcategoryName'];
                        $list['count']=0;
                        $list['city']=$a['destid'];
                        $arr[]=$list;
                    }
                }
            }
        }
        Db::name('dcategories')->insertAll($arr);
    }

    /*
     * 产品：通过城市获取商品，
     * /service/search/products
     */
    public function getGoods(){

        $url = $this->url . '/service/search/products';
        $time = strtotime(date('Y-m-d 00:00:00'));
        $citymsg= db('city')->where('type','CITY')->where('updating','<',$time)
            ->where('destid','>',0)->where('getgoods','1')->find();
        if(empty($citymsg)){
            return false; //结束
        }

        //抓取一年内的商品
        $list['startDate'] = date('Y-m-d');
        $list['endDate'] = date("Y-m-d",strtotime("+1 year",time()));
        $list['destId'] = $citymsg['destid'];
        $list['currencyCode'] = $this->currencyCode;

        //**********************************************
        //先查询中文页，再取英文页补全
        //by suley

        //现有数据库code集
        $code_list = db('goods')->where('city_id',$citymsg['id'])->where('show','2')->column('code');
        $code_list = empty($code_list)?[]:$code_list;

        $api_arr = array('zh'=>$this->zh_header,'en'=>$this->en_header);
        foreach ($api_arr as $k_api_key=>$v_api_key){
            $data = (array)$this->post_curl($url,json_encode($list),[$v_api_key]);
            $data = $this->object_array($data);
            if(!empty($data['data'])){
            //去除数据库已存在的商品
            foreach ($data['data'] as $k=>$a){
                if(in_array($a['code'],$code_list)){
                    unset($data['data'][$k]);
                    }else{
                        $code_list[] = $a['code'];
                }
            }

                if(empty($data['data'])){
                    continue;
                }
                $api_type = $k_api_key=='zh' ? 1 : 0;
                $res = $this->setGoods($data['data'],$citymsg['id'],$citymsg['destid'],$api_type);

                if(empty($res)){
                    continue;
                }
                //中英文Apikey区分标识
                if($k_api_key=='zh'){
                    $this->writeLog("中文key:【ID".$citymsg['id']."城市】新增商品".count($res)."件");
                }else{
                    $this->writeLog("英文key:【ID".$citymsg['id']."城市】新增商品".count($res)."件");
                }

                $arrlist = array_chunk($res,50);
                foreach ($arrlist as $a){
                    db('goods')->insertAll($a);
                }
            }
        }

        db('city')->where('id',$citymsg['id'])->update(['updating'=>time()]);

        $this->writeLog("【ID".$citymsg['id']."城市】抓取完成");

        return true;
    }

    /*
     * 产品:产品数据存表
     */
    public function setGoods($data,$city,$destid,$api_type=0){
        $list=[];
        foreach ($data as $a){
            $arr=[];
            $a=(array)$a;
            $arr['city_id']=$city;
            $arr['destid']=$destid;
            $arr['classify_id']='6';
            $arr['team_id']='1000000';
            $arr['starttime']=time();
            $arr['creattime']=time();
            $arr['updating']=time();
            $arr['show']=2;
            $arr['api_type']=$api_type;
            //viator的产品编码赋值
            $prefix = 'kbxv';
            $arr['goods_tcode']=$prefix.$a['code'];
            $arr['endtime']=strtotime('+5 years');
            $arr['code']=$a['code'];

            $data_detil = $this->goodsDetail($a['code']);
            if(empty($data_detil)){
                continue;
            }
            $data_detil=$this->object_array($data_detil);

            if($data_detil['bookingEngineId']=='FreesaleBE' || $data_detil['bookingEngineId']=='UnconditionalBE'){
                $need_confirm=2;
            }else{
                $need_confirm=1;
            }
            $arr['goods_status']=2; //默认下架
            $arr['need_confirm']=$need_confirm; //二次确认 默认是
            $arr['goods_source']=2; //默认三方
            $arr['isupdated']=0; //更新状态

            $arr['goods_name']=$data_detil['title'];  //商品名称
            $arr['goods_introduce']=$data_detil['shortDescription'];  //商品介绍
            $arr['goods_enintroduce']=$data_detil['shortDescription'];  //英文介绍
            $arr['goods_usetime']=$data_detil['duration'];  //商品用时
            //20210423 修改图片 由一张缩略图修改为productPhotos数组 如果数组为空 则取缩略图
            $arr['goods_image'] = $this->getViatorBannerImages($data_detil['productPhotos'],'photoURL',$data_detil['thumbnailHiResURL']);
//            $arr['goods_image']=$data_detil['thumbnailHiResURL'];  //商品图片
//            if (substr($arr['goods_image'], 0, 7) == 'http://') {
//                $arr['goods_image'] = str_replace("http", "https", $arr['goods_image']);
//            }
            $ppp=str_replace('$','',$data_detil['priceFormatted']);
            $arr['price']=str_replace(',','',$ppp);
            //增加采购价格
            $m_price=str_replace('$','',$data_detil['merchantNetPriceFromFormatted']);
            $arr['merchantNetPrice']=str_replace(',','',$m_price);
            $arr['goods_englishname']=$data_detil['title'];

            if (empty($data_detil['bookingQuestions'])){
                $isquestion=1;
            }else{
                $isquestion=2;
            }
            $arr['isquestion']=$isquestion;
            $arr['bookingEngine']=$data_detil['bookingEngineId'];
            $arr['updatetime']=time();
            $arr['alltravellermessage']=$data_detil['allTravellerNamesRequired']==true?1:0; //旅客全部信息是否填写
            $arr['price_include']='';
            $arr['price_noinclude']='';
            $arr['goods_careful']='';
            $arr['goods_retreating']='';
            if(!empty($data_detil['inclusions'])){
                $arr['price_include']=$this->arrToStr($data_detil['inclusions']); //费用包含
            }
            if(!empty($data_detil['exclusions'])){
                $arr['price_noinclude']=$this->arrToStr($data_detil['exclusions']); //费用不包含
            }
            if(!empty($data_detil['additionalInfo'])){
                $arr['goods_careful']=$this->arrToStr($data_detil['additionalInfo']); //注意事项
            }
            if(!empty($data_detil['termsAndConditions'])){//Viator有退改规则时用他的
                $arr['goods_retreating']=$this->arrToStr($data_detil['termsAndConditions']); //退改
            }else{
                if($data_detil['merchantCancellable']==true){//true可退
                    $cancel_str = "<p><span style='font-size: 14px;'>1.距离服务开始日期前3天外取消更改订单，将会收取0%费用；</span></p><p><span style='font-size: 14px;'>2.距离服务开始时间3天以内取消更改订单，将会收取100%费用。</span></p><p><br/></p>";
                    $arr['merchantCancellable'] = 1;
                }else{//false不可退
                    $cancel_str = "<p><span style='font-size: 14px;'>一经预订，不可取消更改订单，取消更改订单不退款。</span></p><p><br/></p>";
                    $arr['merchantCancellable'] = 0;
                }
                $arr['goods_retreating'] = $cancel_str;
            }
            //语言服务
            $lang='';
            if(!empty($data_detil['tourGrades'])){
                $langlist=[];
                foreach ($data_detil['tourGrades'] as $a){
                    if(empty($a['langServices'])){
                        continue;
                    }
                    foreach ($a['langServices'] as $b){
                        $langlist[$b]=$b;
                    }
                }
                foreach ($langlist as $a){
                    if(empty($lang)){
                        $lang=$a;
                    }else{
                        $lang=$lang.'/'.$a;
                    }
                }
            }

            //其他注意事项
            $arr['goods_careful']=$arr['goods_careful'].'<p>Departure point of tour:'.$data_detil['departurePoint'].'</p><p>Frequency of the tour.：'.$data_detil['operates']
                .'</p><p>Descriptive information on departure times：'.$data_detil['departureTime'].'</p><p>Details of the tour drop-off：'.$data_detil['returnDetails'].'</p><p>Extended description of the product. May contain basic HTML mark-up tags：'.$data_detil['description']
                .'</p><p>Flag to indicate if the tour offers hotel pick up：'.$data_detil['hotelPickup'].'</p><p>票类型：'.$data_detil['voucherOption'].'</p><p>服务语言：'.$lang.'</p>';

            $list[]=$arr;
        }
        return $list;
    }

    /*
     * 产品:获取产品详情
     * /service/product 6379NMISS  20399P2  7641P11
     */
    public function goodsDetail($code='',$show='',$includeProductPhotos=false){

        //**********************************************
        //优先查询中文页
        //by suley
        //$api_key = $this->apiKey_ch;//中文code
        $url=$this->url.'/service/product?code='.$code.'&currencyCode='.$this->currencyCode
            .'&excludeTourGradeAvailability=false&showUnavailable=false';
        $data=$this->get_curl($url,[$this->zh_header]);
        $data=$this->object_array($data)['data'];
        //当中文页不存在时，继续调取英文页
        if(empty($data)){
            //$api_key = $this->apiKey;//英文code
            $url=$this->url.'/service/product?code='.$code.'&currencyCode='.$this->currencyCode
                .'&excludeTourGradeAvailability=false&showUnavailable=false';
            $data=$this->get_curl($url,[$this->en_header]);
            $data=$this->object_array($data)['data'];

            if(empty($data)){
                return false;
            }else{
                $data['api_type'] = 0;//英文Apikey标识
            }
        }else{
            $data['api_type'] = 1;//中文Apikey标识
        }

        unset($data['reviews']); //评论
        if(!$includeProductPhotos) unset($data['productPhotos']); //供应商提供的照片
        if(empty($show)){
            return $data;
        }else{
            return $data[$show];
        }
    }

    /*
     * 详情，测试 可删
     */
    public function goodsDetailapi($code='',$show=''){
        $code=input('code');
        //**********************************************
        //优先查询中文页
        //by suley
        //$api_key = $this->apiKey_ch;//中文code
        $url=$this->url.'/service/product?code='.$code.'&currencyCode='.$this->currencyCode
            .'&excludeTourGradeAvailability=false&showUnavailable=false';
        $data=$this->get_curl($url,[$this->zh_header]);
        $data=$this->object_array($data)['data'];
        //当中文页不存在时，继续调取英文页
        if(!$data){
            //$api_key = $this->apiKey;//英文code
            $url=$this->url.'/service/product?code='.$code.'&currencyCode='.$this->currencyCode
                .'&excludeTourGradeAvailability=false&showUnavailable=false';
            $data=$this->get_curl($url,[$this->en_header]);
            $data=$this->object_array($data)['data'];

            if(!empty($data)){
                $data['api_type'] = 0;//英文Apikey标识
            }
        }else{
            $data['api_type'] = 1;//中文Apikey标识
        }

        unset($data['reviews']); //评论
        unset($data['productPhotos']); //供应商提供的照片

        echo "<pre>";
        var_dump($data);
        echo "</pre>";
        die;
    }

    /*
 * 商品：字段追加
 *
 * eg：https://travelagents.viator.com/tours/Calgary/Calgary-Bow-River-Valley-60-Minute-Segway-Adventure/d817-20399P3
 * Inclusions & Exclusions \ Departure & Return \ What To Expect \ Additional Info \ Cancellation Policy 相关信息全部存入
 * 商品详情字段提取(谷歌翻译):
 * @Inclusions & Exclusions : inclusions/exclusions  包含/不包含
 * @Departure & Return : departurePoint/operates/departureTime/returnDetails 出发点/出发/出发时间/返回
 * @What To Expect : description
 * @Additional Info : additionalInfo 附加信息
 * @Cancellation Policy : termsAndConditions 取消条件
 * 存入说明：Departure & Return出发和返回，关于接送，票类型，Hotel Pickup酒店接送，服务语言 分段存入表字段goods_careful
 * bookingQuestions
 */
    /*
     * 追加商品详情数据 与getgoods合用
     */
    public function addGoodsDetail($code=''){
        $re_list=[];
        $status_time=false;
        if(empty($code)){
            $status_time=true;
            $res=Db::name('goods')->where('updatetime','0')
                ->where('code','<>','')->find();
        }
        if(empty($res)){
            dump('结束');
            die;
        }else{
            $code=$res['code'];
        }

        $data=$this->goodsDetail($code);
        if(empty($data)){
            Db::name('goods')->where('code',$code)->update(['updatetime'=>time()]);
            echo "<script language=JavaScript> location.replace(location.href);</script>";
            die;
        }
        $data=$this->object_array($data);

        $arr=[];
        if($data['bookingEngineId']=='FreesaleBE' || $data['bookingEngineId']=='UnconditionalBE'){
            $need_confirm=2;
        }else{
            $need_confirm=1;
        }
        $arr['classify_id']='6';
        $arr['goods_status']=2; //默认下架
        $arr['need_confirm']=$need_confirm; //二次确认 默认是
        $arr['goods_source']=2; //默认三方
        $arr['isupdated']=0; //更新状态

        $arr['goods_name']=$data['title'];  //商品名称
        $arr['goods_introduce']=$data['shortDescription'];  //商品介绍
        $arr['goods_enintroduce']=$data['shortDescription'];  //英文介绍
        $arr['goods_usetime']=$data['duration'];  //商品用时
        $arr['goods_image'] = $this->getViatorBannerImages($data['productPhotos'],'photoURL',$data['thumbnailHiResURL']);
//            $arr['goods_image']=$data_detil['thumbnailHiResURL'];  //商品图片
//            if (substr($arr['goods_image'], 0, 7) == 'http://') {
//                $arr['goods_image'] = str_replace("http", "https", $arr['goods_image']);
//            }
        $ppp=str_replace('$','',$data['priceFormatted']);
        $arr['price']=str_replace(',','',$ppp);
        $arr['goods_englishname']=$data['title'];
        $arr['code']=$data['code'];

        if (empty($data['bookingQuestions'])){
            $isquestion=1;
        }else{
            $isquestion=2;
        }
        $arr['isquestion']=$isquestion;
        $arr['bookingEngine']=$data['bookingEngineId'];
        $arr['updatetime']=time();
        $arr['alltravellermessage']=$data['allTravellerNamesRequired']==true?1:0; //旅客全部信息是否填写
        $arr['price_include']='';
        $arr['price_noinclude']='';
        $arr['goods_careful']='';
        $arr['goods_retreating']='';
        if(!empty($data['inclusions'])){
            $arr['price_include']=$this->arrToStr($data['inclusions']); //费用包含
        }
        if(!empty($data['exclusions'])){
            $arr['price_noinclude']=$this->arrToStr($data['exclusions']); //费用不包含
        }
        if(!empty($data['additionalInfo'])){
            $arr['goods_careful']=$this->arrToStr($data['additionalInfo']); //注意事项
        }
        if(!empty($data['termsAndConditions'])){//Viator有退改规则时用他的
            $arr['goods_retreating']=$this->arrToStr($data['termsAndConditions']); //退改
        }else{
            if($data['merchantCancellable']==true){//true可退
                $cancel_str = "<p><span style='font-size: 14px;'>1.距离服务开始日期前3天外取消更改订单，将会收取0%费用；</span></p><p><span style='font-size: 14px;'>2.距离服务开始时间3天以内取消更改订单，将会收取100%费用。</span></p><p><br/></p>";
            }else{//false不可退
                $cancel_str = "<p><span style='font-size: 14px;'>一经预订，不可取消更改订单，取消更改订单不退款。</span></p><p><br/></p>";
            }
            $arr['goods_retreating'] = $cancel_str;
        }
        //语言服务
        $lang='';
        if(!empty($data['tourGrades'])){
            $langlist=[];
            foreach ($data['tourGrades'] as $a){
                if(empty($a['langServices'])){
                    continue;
                }
                foreach ($a['langServices'] as $b){
                    $langlist[$b]=$b;
                }
            }
            foreach ($langlist as $a){
                if(empty($lang)){
                    $lang=$a;
                }else{
                    $lang=$lang.'/'.$a;
                }
            }
        }

        //其他注意事项
        $arr['goods_careful']=$arr['goods_careful'].'<p>Departure point of tour:'.$data['departurePoint'].'</p><p>Frequency of the tour.：'.$data['operates']
            .'</p><p>Descriptive information on departure times：'.$data['departureTime'].'</p><p>Details of the tour drop-off：'.$data['returnDetails'].'</p><p>Extended description of the product. May contain basic HTML mark-up tags：'.$data['description']
            .'</p><p>Flag to indicate if the tour offers hotel pick up：'.$data['hotelPickup'].'</p><p>票类型：'.$data['voucherOption'].'</p><p>服务语言：'.$lang.'</p>';

        $data_update=Db::name('goods')->where('code',$code)->update($arr);
        if($status_time){
            echo "<script language=JavaScript> location.replace(location.href);</script>";
        }
    }

    public function addGoodsziduan($code=''){
        $re_list=[];
        $status_time=false;
        if(empty($code)){
            $status_time=true;
            $res=Db::name('goods')->where('updatetime','0')
                ->where('show','2')->find();
        }
        if(empty($res)){
            dump('结束');
            die;
        }else{
            $code=$res['code'];
        }

        $data=$this->goodsDetail($code);
        if(empty($data)){
            Db::name('goods')->where('code',$code)->update(['updatetime'=>time()]);
            echo "<script language=JavaScript> location.replace(location.href);</script>";
            die;
        }
        $data=$this->object_array($data);

        $arr=[];
        dump($code);
        $arr['alltravellermessage']=$data['allTravellerNamesRequired']==true?1:0; //旅客全部信息是否填写
        $arr['updatetime']=time();
        $data_update=Db::name('goods')->where('code',$code)->update($arr);
        if($status_time){
            echo "<script language=JavaScript> location.replace(location.href);</script>";
        }
    }

    /*
    * 更新2 因数据大，格式不统一，尝试MD5
    * type  all 或 sale
    */
    public function updateGoodsmd($code='',$type='all'){
        try {
            $ongo=false;
            //code 为空：执行定时任务  不为空：方法调用
            if(empty($code)){
                $where['show'] = 2;
                $time=strtotime(date('Y-m-d 00:00:00'));
                $where['updating'] = ['LT',$time];

                //只更新已上架商品
                if($type=='sale'){
                    $where['goods_status'] = 1;
                }

                $res=Db::name('goods')->where($where)->find();

                //终止循环
                if(empty($res)){
                    return false;
                }
                //如果不是Viator数据，标记后跳过查找下一条满足的数据
                if(empty($res['code'])){
                    Db::name('goods')->where('goods_id',$res['goods_id'])->update(['isupdated'=>0,'updating'=>time()]);
                    return true;
                }else{
                    $ongo=true;
                    $code=$res['code'];
                }
            }
            $err = 1;
            $data=$this->goodsDetail($code);
            $err = 2;
            $Api_type = isset($data['api_type']) ? $data['api_type'] : 0;//中英文Apikey标识
            $data=$this->object_array($data);
            $list=$this->orderGoods($data);
            $err = 3;

            $table=Db::name('goods_backupsmd5');
            $where=['code'=>$code];
            $resolt=$table->where($where)->find();
            if(empty($resolt)){
                $err = 4;
                $table->insert(['code'=>$list['code']]);
                $err = 5;
                $resolt=$table->where($where)->find();
//                //新增
//                Db::name('goods')->where('code',$code)->update(['updating'=>time(),'api_type'=>$Api_type]);
            }

            $err = 6;
            //判断相似度或是否有改动
            $res=$this->searchGoods($list,$resolt);
            $err = 7;
            if($res){
                $err = 8;
                Db::name('goods')->where('code',$code)->update(['isupdated'=>1,'updating'=>time()]);
                $res_back=Db::name('goods_backups')->where($where)->find();
                if(!empty($res_back)){
                    $err = 10;
                    Db::name('goods_backups')->where($where)->update($list);
                    $err = 11;
                }else{
                    Db::name('goods_backups')->insert($list);
                }
//                    $this->writeLog("【".$code."商品详情更新，Api_key=".$Api_type."】");
            }else{
                $err = 9;
                Db::name('goods')->where('code',$code)->update(['isupdated'=>0,'updating'=>time()]);
//                    $this->writeLog("【".$code."商品详情无更新，Api_key=".$Api_type."】");
            }

            if($ongo==true){
                return true;
            }else{
                die;
            }

        }catch (\Exception $e) {
            $this->writeLog("***************【Error：".$code."出错，err位置=".$err."，e=".$e."】****************");
            $this->writeLog("***************【".$e->getMessage()."】****************");
        }
    }

    /*
     * 更新：数据整理
     */
    public function orderGoods($data){
        $arr=[];
        $arr['code']=$data['code'];  //商品名称
        $arr['goods_name']=$data['title'];  //商品名称
        $arr['goods_englishname']=$data['title'];
        $ppp=str_replace('$','',$data['priceFormatted']);
        $arr['price']=str_replace(',','',$ppp);

        //增加采购价格
        $m_price=str_replace('$','',$data['merchantNetPriceFromFormatted']);
        $arr['merchantNetPrice']=str_replace(',','',$m_price);

        $arr['goods_introduce']=$data['shortDescription'];  //商品介绍
        $arr['goods_usetime']=$data['duration'];  //商品用时
        $arr['price_include']='';
        $arr['price_noinclude']='';
        $arr['goods_careful']='';
        $arr['goods_retreating']='';
        $arr['goods_image'] = $this->getViatorBannerImages($data['productPhotos'],'photoURL',$data['thumbnailHiResURL']);
//            $arr['goods_image']=$data_detil['thumbnailHiResURL'];  //商品图片
//            if (substr($arr['goods_image'], 0, 7) == 'http://') {
//                $arr['goods_image'] = str_replace("http", "https", $arr['goods_image']);
//            }
        //以下为需要但详情页不显示
        if (empty($data['bookingQuestions'])){
            $isquestion=1;
        }else{
            $isquestion=2;
        }
        $arr['isquestion']=$isquestion;
        $arr['goods_enintroduce']=$data['shortDescription'];  //英文介绍
        $arr['bookingEngine']=$data['bookingEngineId'];
        $arr['allTravellerNamesRequired']=$data['allTravellerNamesRequired']==true?1:0;;
        $arr['updating']=time();

        if(!empty($data['inclusions'])){
            $arr['price_include']=$this->arrToStr($data['inclusions']); //费用包含
        }
        if(!empty($data['exclusions'])){
            $arr['price_noinclude']=$this->arrToStr($data['exclusions']); //费用不包含
        }
        if(!empty($data['additionalInfo'])){
            $arr['goods_careful']=$this->arrToStr($data['additionalInfo']); //注意事项
        }
        if(!empty($data['termsAndConditions'])){//Viator有退改规则时用他的
            $arr['goods_retreating']=$this->arrToStr($data['termsAndConditions']); //退改
        }else{
            if($data['merchantCancellable']==true){//true可退
                $arr['merchantCancellable'] = 1;
                $cancel_str = "<p><span style='font-size: 14px;'>1.距离服务开始日期前3天外取消更改订单，将会收取0%费用；</span></p><p><span style='font-size: 14px;'>2.距离服务开始时间3天以内取消更改订单，将会收取100%费用。</span></p><p><br/></p>";
            }else{//false不可退
                $arr['merchantCancellable'] = 0;
                $cancel_str = "<p><span style='font-size: 14px;'>一经预订，不可取消更改订单，取消更改订单不退款。</span></p><p><br/></p>";
            }
            $arr['goods_retreating'] = $cancel_str;
        }
        //语言服务
        $lang='';
        if(!empty($data['tourGrades'])){
            $langlist=[];
            foreach ($data['tourGrades'] as $a){
                if(empty($a['langServices'])){
                    continue;
                }
                foreach ($a['langServices'] as $b){
                    $langlist[$b]=$b;
                }
            }
            foreach ($langlist as $a){
                if(empty($lang)){
                    $lang=$a;
                }else{
                    $lang=$lang.'/'.$a;
                }
            }
        }

        //其他注意事项
        $arr['goods_careful']=$arr['goods_careful'].'<p>Departure point of tour:'.$data['departurePoint'].'</p><p>Frequency of the tour.：'.$data['operates']
            .'</p><p>Descriptive information on departure times：'.$data['departureTime'].'</p><p>Details of the tour drop-off：'.$data['returnDetails'].'</p><p>Extended description of the product. May contain basic HTML mark-up tags：'.$data['description']
            .'</p><p>Flag to indicate if the tour offers hotel pick up：'.$data['hotelPickup'].'</p><p>票类型：'.$data['voucherOption'].'</p><p>服务语言：'.$lang.'</p>';

        return $arr;
    }

    /*
     * 更新：相似度判断
     */
    public function searchGoods($data,$res){
        unset($data['goods_image']); //图片不做对比
        $delstr=['allTravellerNamesRequired','price','merchantNetPrice','isquestion','bookingEngine','goods_enintroduce','goods_retreating','merchantCancellable'];//不在显示的字段 自主更新
        $updatStatus=false; //更新状态
        $list=[]; //自主更新字段 fuck 自己挖坑
        $list1=[]; //自主更新字段 fuck 自己挖坑
        foreach ($data as $key=>$value){
            if($key=='updating'){
                continue;
            }
            $md1=md5($value);
            $md2=md5($res[$key]);

            if($md1==$md2){
                continue;
            }

            if(in_array($key,$delstr)){
                $list[$key]=$value;
                if($key=='allTravellerNamesRequired'){
                    $list1['alltravellermessage']=$value;
                }else{
                    $list1[$key]=$value;
                }
            }else{
                $updatStatus=true;
            }
        }
        if(!empty($list)){
            $where['code']=$res['code'];
            Db::name('goods')->where($where)->update($list1);
            Db::name('goods_backupsmd5')->where($where)->update($list);
        }
        return $updatStatus;
    }

    /*
     * 定时：更新商品   仅更新上架商品
     */
    public function timeStart(){
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//让程序一直执行下去

        $this->writeLog("【timeStart】开始更新上架商品【测试环境】");
        $run_num = 0;

        $timing=true;//结束条件
        do{
            $timing=$this->updateGoodsmd('','sale');
            //强行终止
            $goonStatus=Db::name('goods_price')->where('id',1)->find()['time'];
            if($goonStatus=='1'){
                $timing=false;
            }
            $run_num++;
        }while($timing);
        $this->writeLog("【timeStart】抓取结束,共循环".$run_num."次【测试环境】");
    }

    /*
     * 定时：更新全部商品
     */
    public function timeStartAll(){
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//让程序一直执行下去

        $this->writeLog("【timeStartAll】开始更新商品【测试环境】");
        $run_num = 0;

        $timing=true;//结束条件
        do{
            $timing=$this->updateGoodsmd();
            //强行终止
            $goonStatus=Db::name('goods_price')->where('id',1)->find()['time'];
            if($goonStatus=='1'){
                $timing=false;
            }
            $run_num++;
//            sleep($interval);//等待时间，进行下一次操作。
        }while($timing);
        $this->writeLog("【timeStartAll】抓取结束,共循环".$run_num."次【测试环境】");
    }

    /*
     * 定时：缓存三方价格
     */
    public function timePrice($code=''){
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//让程序一直执行下去

        $timing=true;  //结束条件
        //所有待获取的商品
        $where=[
            'goods_status'=>1,  //售卖中
            'show'=>2,  //第三方的
        ];
        if(empty($code)){
            $this->writeLog("【timePrice】开始更新价格");
            $goodsList=Db::name('goods')->where($where)->field('code')->select();
            $stats=1;
        }else{
            $goodsList[]=['code'=>$code];
            $stats=2;
            $no_flag= 0;//是否未取到有价格的日期   1未取到  0有取到
            $timing=false;
        }
        if (empty($goodsList)) die;

        //查询的月份
        $month=date('m');
        $lastMonth=date('m',strtotime('+1 month'));

        //增至六个月
        $lastMonth_3=date('m',strtotime('+2 month'));
        $lastMonth_4=date('m',strtotime('+3 month'));
        $lastMonth_5=date('m',strtotime('+4 month'));
        $lastMonth_6=date('m',strtotime('+5 month'));

        do{
            if (empty($goodsList)) $timing=false;  //终止条件
            //获取code和商品信息
            $code=array_pop($goodsList)['code'];  //当前商品

            $goodsdetail=$this->goodsDetail($code);
            if(!empty($goodsdetail['ageBands'])){
                cache($code.'ageBands',$goodsdetail['ageBands']);
            }else{
                cache($code.'ageBands',[]);
            }

            if(empty($goodsdetail)){
                if($stats==1){
                    $updateArr['accidentDrop'] = 1;//记录意外下架
                }else{
                    $no_flag = 1;
                    $updateArr['goods_status'] = 2;
                }

                //商品下架
                Db::name('goods')->where('code',$code)->where('show','2')->update($updateArr);

                //执行标品下架
                $standard = db("standard")
                    ->alias("s")
                    ->join("goods g","s.goods_id=g.goods_id","left")
                    ->where("g.code",$code)
                    ->field("s.id")
                    ->find();
                if(!empty($standard)){
                    db("standard")->where('id',$standard['id'])->update(['show_toB'=>0]);
                    //es 删除该商品
                    (new Esapi())->delStandardDoc($standard['id']);
                    //通知相应供应商下架该商品
                    (new KbxOrder())->pullOffShelvesNotifyToKbx($standard['id']);
                    //服务号通知供应商下架通知
                    //(new KbxOrder())->sendProductOffAlertNotify($standard);
                }

                continue;
            }

            //获取价格 3902LANDSEA3
            $resArray1=$this->getPriceShow($code,$month,$goodsdetail['ageBands']);
            $resArray2=$this->getPriceShow($code,$lastMonth,$goodsdetail['ageBands']);

            //获取价格范围增至六个月
            $resArray3=$this->getPriceShow($code,$lastMonth_3,$goodsdetail['ageBands']);
            $resArray4=$this->getPriceShow($code,$lastMonth_4,$goodsdetail['ageBands']);
            $resArray5=$this->getPriceShow($code,$lastMonth_5,$goodsdetail['ageBands']);
            $resArray6=$this->getPriceShow($code,$lastMonth_6,$goodsdetail['ageBands']);

            if(empty($resArray1)){
                $res_arr = array();
                if(!empty($resArray2)){
                    $resArray1=$resArray2;
                    $res_arr = array($resArray3,$resArray4,$resArray5,$resArray6);
                }else{
                    if(!empty($resArray3)){
                        $resArray1=$resArray3;
                        $res_arr = array($resArray4,$resArray5,$resArray6);
                    }else{
                        if(!empty($resArray4)){
                            $resArray1=$resArray4;
                            $res_arr = array($resArray5,$resArray6);
                        }else{
                            if(!empty($resArray5)){
                                $resArray1=$resArray5;
                                $res_arr = array($resArray6);
                            }else{
                                if(!empty($resArray6)){
                                    $resArray1=$resArray6;
                                }
                            }
                        }
                    }
                }
            }else{
                $res_arr = array($resArray2,$resArray3,$resArray4,$resArray5,$resArray6);
            }

            foreach ($res_arr as $res_v) {
                if(!empty($res_v)){
                    foreach ($res_v as $a=>$d){
                        if(!isset($resArray1[$a])){
                            $resArray1[$a]=[];
                        }
                        foreach ($d as $k){
                            array_push($resArray1[$a],$k);
                        }
                    }
                }
            }


            if(is_array($resArray1)){
                $resArray1=array_filter($resArray1);
            }else{
                $resArray1='';
            }

            //补充 如果六个月内没有价格 则商品下架
            if(empty($resArray1)){
                if($stats==1){
                    $updateArr['accidentDrop'] = 1;//记录意外下架
                }else{
                    $no_flag = 1;
                    $updateArr['goods_status'] = 2;
                }
                Db::name('goods')->where('code',$code)->where('show','2')->update($updateArr);

                //执行标品下架
                $standard = db("standard")
                    ->alias("s")
                    ->join("goods g","s.goods_id=g.goods_id","left")
                    ->where("g.code",$code)
                    ->field("s.id")
                    ->find();
                if(!empty($standard)){
                    db("standard")->where('id',$standard['id'])->update(['show_toB'=>0]);
                    //es 删除该商品
                    (new Esapi())->delStandardDoc($standard['id']);
                    //通知相应供应商下架该商品
                    (new KbxOrder())->pullOffShelvesNotifyToKbx($standard['id']);
                    //服务号通知供应商下架通知
                    //(new KbxOrder())->sendProductOffAlertNotify($standard);
                }

                continue;
            }else{
                $endtime=[];
                foreach ($resArray1 as $a){
                    $endtime[]=strtotime($a[0]['bookingDate']);
                }
                $endtime=min($endtime);
                $nexttime=strtotime('+5 month');
                $lasttime=strtotime(date('Y-m-t 23:00:00',$nexttime));
                if($endtime>$lasttime){
                    if($stats==1){
                        $updateArr['accidentDrop'] = 1;//记录意外下架
                    }else{
                    $updateArr['goods_status'] = 2;
                    }
                    Db::name('goods')->where('code',$code)->where('show','2')->update($updateArr);
                    continue;
                }
            }


            //比较价格是否有变动
            $this->comparePrice($code,$resArray1);

            //获取套餐分类
            $tourGrades=$this->getGrend($code,$goodsdetail['tourGrades']);

            //将没有价格的分类去掉
            $temp_key=[];
            foreach ($resArray1 as $res_key=>$res_val){
                $temp_key[]=$res_key;
            }
            foreach ($tourGrades as $grade_key=>$grade){
                if(!in_array($grade['gradeCode'],$temp_key)){
                    unset($tourGrades[$grade_key]);
                }
            }

            $resArray1["month_num"] = 6;

            //价格缓存

            cache($code.'price',$resArray1);
            //套餐类型缓存
            cache($code.'type',$tourGrades);

            //数据库写入记录
            $time=date('Y-m-d H:i:s');
            $res=Db::name('goods_price')->where('code',$code)->find();
            if($res){
                Db::name('goods_price')->where('code',$code)->update(['time'=>$time]);
            }else{
                $data=[
                    'code'=>$code,
                    'time'=>$time
                ];
                Db::name('goods_price')->insert($data);
            }

            //强行终止
            $goonStatus=Db::name('goods_price')->where('id',1)->find()['time'];
            if($goonStatus=='1'){
                $timing=false;
            }
        }while($timing);
        if($stats==1){
            $this->writeLog("【timePrice】抓取结束");
            dump('抓取结束');
        }else{
            if($no_flag==1){
                return 401;
            }else{
                return 200;
            }
        }
    }

    /*
     * 定时：自动更新产品信息
     */
    public function timeUpdateGoods(){
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//让程序一直执行下去
        $timing=true;  //结束条件

        $this->writeLog("【timeUpdateGoods】开始更新商品");

        do{
            $timing=$this->getGoods();
            //强行终止
            $goonStatus=Db::name('goods_price')->where('id',1)->find()['time'];
            if($goonStatus=='1'){
                $timing=false;
            }
        }while($timing);
        $this->writeLog("【timeUpdateGoods】抓取结束");
    }

    /*
     * 定时：viator 订单查询定时
     */
    public function timeOrder(){
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//让程序一直执行下去
        $KbxOrder = new KbxOrder();
        $kbxorder = $KbxOrder->kbx_order_confirmation();
        if(count($kbxorder)==0){
            dump('状态修改结束！');die;
        }

        echo "共有".count($kbxorder)."个待确认订单";
        echo "*********************************************<br>";

        foreach ($kbxorder as $every){
            $email = $every['details']['bookerEmail'];
            $itineraryId = $every['details']['itineraryId'];
            $result_status = $this->viatorOrder($email,$itineraryId);
            if($result_status['status']==1){
                echo $every['orderNo']."还未未确认完毕";
                continue;
            }
            $goodsid = $every['goods']['goodsId'];
            $datas= db('goods')->alias('a')->where('a.goods_id',$goodsid)->join('city b','b.id=a.city_id')->field('a.goods_name,b.name,need_confirm')->find();

            //订单系统  更新order数据  查询二次确认状态修改
            $postUpdateArr = [
                'id'=>$every['id'],
                'details'=>$result_status['res'],
                'speedStatus'=>$result_status['status'],//二次确认进度
            ];
            $update_res = $KbxOrder->kbx_operate_order($every['orderType'],$postUpdateArr);
            $log[]=[
                '订单系统API：二次确认状态修改'=>json_encode($postUpdateArr),
                'res'=>$update_res
            ];
            Log::record($log);

            echo $every['orderNo']."确认完毕，结果为：".$result_status['status'];

            // 返回 2 确认完成，下单失败  3确认完成，下单成功
            if($result_status['status']==2){
                $member=db('member')->where('member_id',$every['booker']['memberId'])->find();
                $content2= $member['member_nickname']."用户于 ".date('Y-m-d',strtotime($every['createdAt'])) ." 购买的商品 <a>".$datas['name'] ."</a> 的<a> ".$datas['goods_name'] ."</a>预订失败，
    订单号<a> ".$every['orderNo'] ."</a>  。可进入<a href='https://c.kuaibangxing.com/admin/common/login'>快帮行</a>后台系统确认";

                //退款
                $Orderuser=new Order();
                $msg=new Msg();
                if(!isset($every['payType'])){
                    $every['payType'] = 1;
                }
                if($every['payType']==2){//信用卡支付
                    $credit_charge = model('Accounts')->where('order_no',$every['orderNo'])->find();
                    $refund_res = $msg->kbxCreditRefund($credit_charge['credit_charge_id'],"后台退款");
                    if ($refund_res['status']==='succeeded'){//退款成功
                        //退款成功
                        $postUpdateArr = [
                            'id'=>$every['id'],
                            'statusPhp'=>array(
                                'orderStatus'=>8,
                            ),
                            'status'=>array(
                                'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                            ),
                            'refund'=>array(
                                'refundMoney'=>$every['payments']['foldMoney'],
                                'refundStatus'=>2,
                            ),
                        ];
                        $update_res = $KbxOrder->kbx_operate_order($every['orderType'],$postUpdateArr);
                        $log[]=[
                            '订单系统API：二次确认预约不成功-退款成功'=>json_encode($postUpdateArr),
                            'res'=>$update_res
                        ];
                        Log::record($log);

                        if($update_res){
                            $md=model('Accounts')->insert([
                                'member_id'=>$every['booker']['memberId'],
                                'order_no'=>$every['orderNo'],
                                'accounts_money'=>$credit_charge['accounts_money'],
                                'business_way'=>4,
                                'description'=>"后台退款",
                                'credit_charge_id' => $credit_charge['credit_charge_id'],//支付id
                                'credit_charge_data' => json_encode($refund_res,true),//返回的退款data
                                'creattime'=>date('YmdHis',time())
                            ]);
                        }
                        // 下单 失败短信通知
                        $content1='【快帮行】您好，您的订单预订失败，退款已原路返回您的信用卡账户，请重新下单或选择其他同类线路产品。请联系国内客服: +86 400-100-5295；北美客服: +1 800-932-1178，进入人工通道解决您的问题。感谢您对快帮行的关注。';
                    }else{//退款失败
                        //退款失败
                        $postUpdateArr = [
                            'id'=>$every['id'],
                            'statusPhp'=>array(
                                'orderStatus'=>8,
                            ),
                            'status'=>array(
                                'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                            ),
                            'refund'=>array(
                                'refundMoney'=>$every['payments']['foldMoney'],
                                'refundStatus'=>2,
                            ),
                        ];
                        $update_res = $KbxOrder->kbx_operate_order($kbxorder['orderType'],$postUpdateArr);
                        $log[]=[
                            '订单系统API：二次确认预约不成功-退款失败'=>$every['orderNo'],
                        ];
                        Log::record($log);

                        $title='自动退款失败';
                        $res='订单号为'.$every['order_no'].'的订单，退款失败，原因为'.$refund_res['msg'].'请尽快处理！';
                        $msg->kbxemailcode($title,$res,'david@kuaibangxing.com');
                        // 下单 失败短信通知
                        $content1='【快帮行】您好，您的订单预订失败，很抱歉，自动退款出现异常，请联系国内客服: +86 400-100-5295；北美客服: +1 800-932-1178，进入人工通道解决您的问题。感谢您对快帮行的关注。';
                    }
                }else {//pay_type==1 微信支付
                    $aa= $Orderuser->WxRefund($every['orderNo'].'KBX1230967564',$every['payments']['foldMoney'],$every['payments']['foldMoney']);
                    if ($aa===true){
                        //退款成功
                        $postUpdateArr = [
                            'id'=>$every['id'],
                            'statusPhp'=>array(
                                'orderStatus'=>8,
                            ),
                            'status'=>array(
                                'orderStatus'=>$this->statusArr[8]['orderStatus'],
                                'paymentStatus'=>$this->statusArr[8]['paymentStatus'],
                            ),
                            'refund'=>array(
                                'refundMoney'=>$every['payments']['foldMoney'],
                                'refundStatus'=>2,
                            ),
                        ];
                        $update_res = $KbxOrder->kbx_operate_order($every['orderType'],$postUpdateArr);
                        $log[]=[
                            '订单系统API：二次确认预约不成功-退款成功'=>json_encode($postUpdateArr),
                            'res'=>$update_res
                        ];
                        Log::record($log);
                        if($update_res){
                            $md=Db::name('Accounts')->insert([
                                'member_id'=>$every['booker']['memberId'],
                                'accounts_money'=>$every['payments']['foldMoney'],
                                'business_way'=>4,
                                'creattime'=>date('YmdHis',time())
                            ]);
                        }
                        // 下单 失败短信通知
                        $content1='【快帮行】您好，您的订单预订失败，退款已原路返回您的微信账户，请重新下单或选择其他同类线路产品。请联系国内客服: +86 400-100-5295；北美客服: +1 800-932-1178，进入人工通道解决您的问题。感谢您对快帮行的关注。';
                    }else{
                        $title='自动退款失败';
                        $res='订单号为'.$every['orderNo'].'的订单，退款失败，原因为'.$aa.'请尽快处理！';
                        $msg->kbxemailcode($title,$res,'david@kuaibangxing.com');
                        // 下单 失败短信通知
                        $content1='【快帮行】您好，您的订单预订失败，很抱歉，自动退款出现异常，请联系国内客服: +86 400-100-5295；北美客服: +1 800-932-1178，进入人工通道解决您的问题。感谢您对快帮行的关注。';
                    }
                }
            }else if($result_status['status']==3){
                $member=db('member')->where('member_id',$every['booker']['memberId'])->find();
                $content1= "
        <p><b>尊敬的 ".$member['member_nickname']." ，您好：</b></p>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;您的订单已预订成功，祝您出行愉快，快帮行与您一路同行。</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;产品：".$datas['name'] ."下的".$datas['goods_name']."</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;订单号：".$every['orderNo'] ."</p>

<p>&nbsp;&nbsp;&nbsp;&nbsp;使用日期：".date('Y-m-d',strtotime($every['itinerary']['travelDate'])) ."</p>
 
<p>&nbsp;&nbsp;&nbsp;&nbsp;您可以在快帮行公众号（kwibon）点击底部菜单“发现”-“我的”进入个人中心 查看最新订单状态，本订单完成之后您将获取   <a href=''style='color:#ff7d00 '> ".(int)$every['payments']['addIntegral']."</a>积分，预祝您的行程愉快！</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;有任何问题，请联系我们</p> 

<div style='opacity:1;position: relative;'>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 国内客服: <a>+86 400-100-5295</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 北美客服: <a>+1 800-932-1178</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp;* 客服微信：<a>kbxmei</a></p>
    <p>&nbsp;&nbsp;&nbsp;&nbsp; 官网：<a href='http://www.kuaibangxing.com'>http://www.kuaibangxing.com</a></p>
         <div style=' position: absolute ;background: url(https://c.kuaibangxing.com/uploads/admin/admin_thumb/20181011/f559459c585157808d9c95ee040b03cc.png) no-repeat 5% 5% ;width: 50%;bottom:-9px;height: 150px;
opacity:0.08; background-size: 300px; '>  </div> 
            
            </div>
        ";

                $content2= $member['member_nickname']."用户于 ".date('Y-m-d',strtotime($every['createdAt'])) ." 购买的商品 <a>".$datas['name'] ."</a> 的<a> ".$datas['goods_name'] ."</a>已预订成功，
    订单号<a> ".$every['orderNo'] ."</a>  。可进入<a href='https://c.kuaibangxing.com/admin/common/login'>快帮行</a>后台系统确认";
            }
            $subject1='快帮行商品购买通知';
            $subject2='订单二次确认通知';
            $address1=isset($every['contact']['email']) ? $every['contact']['email'] : 'david@kuaibangxing.com';
            $address2='david@kuaibangxing.com';

            $msg=new Msg();
            //邮箱
            $d=$msg->kbxemailcode($subject1,$content1,$address1);

            echo "<br>";
            echo $every['orderNo']."发送邮件1";

            $d1=$msg->kbxemailcode($subject2,$content2,$address2);

            echo "<br>";
            echo $every['orderNo']."发送邮件2";

            //太乱了 发送凭证和短信单独写
//            $msg->duanxin($every);
            $voucherUrl = "<p><b><a href='https://prelive.viatorapi.viator.com/service/merchant/voucher.jspa?code=".$every['details']['voucherKey']."&embedResources=false'>点击下载凭证</a></b></p><br>";

            $log[]=[
                '二次确认成功发送voucherUrl'=>$voucherUrl,
            ];
            Log::record($log);

            $title=$every['orderNo'];
            $msg->kbxemailcode($title,$voucherUrl,'david@kuaibangxing.com');

            echo "<br>";
            echo $every['orderNo']."发送凭证<>";
        }
        dump('状态修改结束！');
    }

    /*
     * 支付回调有问题 固定测试
     */
    public function emailpass(){
        $order=cache('order');
        dump($order);
        die;
    }

    /*
     * 查看价格缓存
     */
    public function getPriceCache(){
        $code=input('code');
        $price = cache($code.'price');
        $type = cache($code.'type');
        return json_encode(['price'=>$price,'type'=>$type]);
    }

    /*
     * 临时测试方法
     * 对比两张表
     */
    public function unify(){
        $data=Db::name('city')->alias('a')
            ->join('dclcity d','a.name=d.name')
            ->field('a.id as id,d.id as destid,d.type as type')
            ->select();
        dump($data);
        foreach ($data as $a){
            Db::name('city')->update($a);
        }
    }

    /*
     * 中文翻译
     */
    public function addname(){
        $data=Db::name('dclcity')->order('id')->select();
        foreach ($data as $d){
            $name=$this->etocTencent($d['ename'],'EN','zh-CHS');
            Db::name('dclcity')->where('id',$d['id'])->update(['name'=>$name]);
        }
    }

    /*
     * 订单：发起预约 主要联系人
     * /service/booking/book
     */
    public function bookingUser($data='',$question='',$orderId='',$orderType=''){
        //下单固定快帮行电话和邮箱
        $kbx_email='support@kuaibangxing.com';
        if(rand(1,100)>50){
            $kbx_phone="+864001005295";
        }else{
            $kbx_phone="+18009321178";
        }

        $currencyCode=$this->currencyCode;
        $url = $this->url.'/service/booking/book';
        $de_bug=true; //调试模式 正式下单改为false
        $order=$data['order'];
        //建立基本参数
        $list=[
            'demo'=>$de_bug,
            "currencyCode"=> $currencyCode,  //货币方式
            "partnerDetail"=> [  //合作伙伴必须在partnerDetails对象中传递一个distributorRef atitinerary级别
                "distributorRef"=> "distributorRef".$data['order'],
            ],
            'booker'=>[   //主要联系人的信息
                'firstname'=>$data['orderuser']['firstname'],    //主要联系人的名字
                'surname'=>$data['orderuser']['surname'],   //姓
//                'title'=>$data['orderuser']['title'],       //主要联系人的头衔  *非必须*
                'email'=>$kbx_email,        // 固定 由相关改动由他们转发
                'homePhone'=>$kbx_phone,   //主要联系电话
            ],
            'items'=>[
                [
                    'partnerItemDetail'=>[  //对于项目级别的额外合作伙伴细节，对于任何一个合作伙伴或商业伙伴
                        'distributorItemRef'=>'distributorItemRef'.$data['order'],
                    ],
                    'hotelId'=>null,  // local 、notBooked 、notListed    /booking/hotels中可以看到该产品的酒店列表
                    'pickupPoint'=>null,  //酒店接送点相关信息 产品返回hotelPickup:正确，在/booking/hotels中可以看到该产品的酒店列
                    'travelDate'=>$data['time'],   //项目的旅行日期
                    'productCode'=>$data['code'],
                    'tourGradeCode'=>$data['tourGradeCode'],    //预定项目的旅游代码
                    'languageOptionCode'=>'en/SERVICE_GUIDE',   //为该产品提供的语言服务
                    'bookingQuestionAnswers'=>[],
                    'specialRequirements'=>'',    //获取预订的任何额外需求，
                    'travellers'=>$data['bandiduser']
                ]
            ]
        ];

        //预约问题
        if (!empty($question)){
            foreach ($question as $k){
                $list['items'][0]['bookingQuestionAnswers'][]=$k;
            }
        }

        //判断姓名
        if(strlen($list['booker']['firstname'])<2 || strlen($list['booker']['surname'])<2){
            return ['code'=>'001','msg'=>'请确认联系人姓名长度大于2位！','id'=>0];
        }
        foreach ($list['items'][0]['travellers'] as $a){
            if(strlen($a['firstname'])<2 || strlen($a['surname'])<2){
                return ['code'=>'001','msg'=>'请确认每位出行人员姓名长度大于2位！','id'=>0];
            }
        }
        //开始下单
        $data=$this->post_curl($url,json_encode($list),[$this->en_header]);
        $data=$this->object_array($data);

        $log[]=[
            'Viator_booking_data'=>$data,
        ];
        Log::record($log);

        if (!empty($data['errorMessage'])) {
            $postUpdateArr = [
                'id'=>$orderId,
                'details'=>$data,
                'detailsFrom'=>'viator',
            ];
            $KbxOrder = new KbxOrder();
            $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);

            $log[]=[
                '订单系统API：viator下单失败数据更新'=>json_encode($postUpdateArr),
                'res'=>$update_res
            ];
            Log::record($log);

            return ['code'=>'001','msg'=>$data['errorMessage'],'id'=>$order,'data'=>$data];
        } else {
            $data=$data['data'];
            $list=[
                'order_no'=>$order,
                'email'=>$data['bookerEmail'],
                'speedstatus'=>$data['itemSummaries'][0]['bookingStatus']['type'],
                'itemId'=>$data['itemSummaries'][0]['itemId'],
                'itineraryId'=>$data['itemSummaries'][0]['itineraryId'],
                'destId'=>$data['itemSummaries'][0]['destId'],
                'travelDate'=>$data['itemSummaries'][0]['travelDate'],
                'bookingDate'=>$data['bookingDate'],
                'voucherKey'=>$data['itemSummaries'][0]['voucherKey'],
                'securityToken'=>$data['securityToken'],
                'distributorItemRef'=>$data['itemSummaries'][0]['distributorItemRef'],
                'distributorRef'=>$data['distributorRef'],
                'languageServicesLanguageCode'=>$data['itemSummaries'][0]['languageServicesLanguageCode'],
                'tourGradeCode'=>$data['itemSummaries'][0]['tourGradeCode'],
                'productCode'=>$data['itemSummaries'][0]['productCode'],
                'lastRetailPriceFormatted'=>$data['totalPriceFormatted'],
                'merchantCancellable'=>$data['itemSummaries'][0]['merchantCancellable'],
                'satus'=>2,
                'type'=>$de_bug==true?1:0,
                'total_json'=>json_encode($data)
            ];

            $postUpdateArr = [
                'id'=>$orderId,
                'details'=>$data,
                'supplier'=>array(
                    'cost'=>array(
                        'currency'=>'USD',
                        'amount'=>$data['totalPriceUSD']
                    )
                ),
                'detailsFrom'=>'viator',
            ];
            $KbxOrder = new KbxOrder();
            $update_res = $KbxOrder->kbx_operate_order($orderType,$postUpdateArr);

            $log[]=[
                '订单系统API：viator下单数据更新'=>json_encode($postUpdateArr),
                'res'=>$update_res
            ];
            Log::record($log);

            return ['code'=>'002','msg'=>'下单成功','id'=>$orderId,'data'=>$list];
        }
    }

    /*
     * 调试使用 上线及删
     */
    public function showCache(){
        $data=cache('booking');
        dump($data);
    }

    /*
     * 订单：修改旅客真实姓名
     */
    public function AmendName($orderid=''){
        //查询订单流水 1003912841  577728781

        $itineraryItemId='240003411';
        $securityToken='961e0c6d4aab05789d5f17e6b96c66e12609084fbe5d13a217c815b582cf7c4c';
        $userId='862522446@qq.com';
        $url = $this->url.'/service/booking/'.$itineraryItemId.'/amendTravellers';
        $data=[
            'travellerAmendments'=>[
                [
                    '@class'=>'traveller',
                    'lead'=>'false',
                    'available'=>'true',
                    'title'=>'Mr',
                    'firstname'=>'Traveller',
                    'lastname'=>'Traveller3',
                    'age'=>'30',
                    'ageBand'=>'ADULT',
                    'changeAction'=>'ADD_TRAVELLER',
                ],
                [
                    '@class'=>'traveller',
                    'lead'=>'false',
                    'available'=>'true',
                    'title'=>'Mr',
                    'firstname'=>'Traveller',
                    'lastname'=>'Traveller3',
                    'age'=>'30',
                    'ageBand'=>'ADULT',
                    'changeAction'=>'REMOVE_TRAVELLER',
                ]
            ],
//            'quote'=>'',
        ];
        $header=[
            'User-Id:'.$userId,
            'Security-Token:'.$securityToken,
            $this->en_header
        ];
        $res=$this->post_curl($url,json_encode($data),$header);
        dump($res);
    }

    /*
     * 订单：撤消订单
     */
    public function cancelBooking($data){
        $url = $this->url.'/service/merchant/cancellation';
        $res=$this->post_curl($url,json_encode($data),[$this->en_header]);
        $log[]=[
            'Viator撤销订单结果'=>$res,
        ];
        Log::record($log);
        return $res;

    }

    /*
     * 订单：显示可用的旅游日程表,零售价格将代表旅游的“起点”价格
     * /service/booking/availability
     */
    public function getPrice($code='10211P14',$month='10'){
        //请求路由
        $url = $this->url . '/service/booking/availability';
        //获取请求的月份 大于当前月则表示明年的请求月份
        $year = date('Y');
        $now_month = date('m');
        if($month < $now_month){
            $year = $year + 1;
        }
        $list=[
            'productCode'=>$code,
            'month'=>$month,
            'year'=>$year,
            'currencyCode'=>$this->currencyCode,
            'ageBands'=>[
                [
                    'bandId'=>1,
                    'count'=>2
                ],
//                [
//                    'bandId'=>2,
//                    'count'=>1
//                ],
//                [
//                    'bandId'=>3,
//                    'count'=>1
//                ]
            ]
        ];
        //发送post
        $result = $this->post_curl($url,json_encode($list),[$this->en_header]);
        $result = $this->object_array($result);
        return json_encode($result);
    }

    /*
     * 订单：换个接口获取价格 奇葩样例：6349NIGHT 10211P14
     */
    public function getPriceShow($code='',$month='',$ageBands=''){
        $month=empty($month)?date('m'):$month;
        $url = $this->url . '/service/booking/availability/tourgrades/pricingmatrix';
        $currencyCode=$this->currencyCode;
        $month_1=date('m');
        $year=date('Y');
        if($month<$month_1){
            $year=$year+1;
        }
        $list=[
            'productCode'=>$code,
            'month'=>$month,
            'year'=>$year,
            'currencyCode'=>$currencyCode
        ];
        $data=$this->post_curl($url,json_encode($list),[$this->en_header]);
        $data=$this->object_array($data);

        if(empty($data['data'])){
            return '';
        }
        //年龄组
        $age_list=[];
        if(empty($ageBands)){
            $ageBands=$this->goodsDetail($code,'ageBands');
        }
        foreach ($ageBands as $w){
            $age_list[$w['bandId']]['description']=$w['description'];
            $age_list[$w['bandId']]['age']=$w['ageFrom'].'-'.$w['ageTo'];
        }

        //取出有价格的日期
        $data=$data['data']['dates'];

        $res_list=[];//返回的数据
        $code_err=false;

        if(!is_array($data)) return '';

        foreach ($data as $k){
            foreach ($k['tourGrades'] as $j){  //gradeCode
                //由于对于返回结果不明确 记录异常商品
                if(count($j['pricingMatrix'])>1){
                    $code_err=true;
                    $temp_price=[];
                    foreach ($j['pricingMatrix'] as $l){ //bookingDate
                        $temp=[
                            'bookingDate'=>$l['bookingDate'],
                            'ageBands'=>[]
                        ];
                        foreach ($l['ageBandPrices'] as $h){ //bandId min max
                            $merchantNetPrice = $h['prices'][0]['merchantNetPrice'];
                            $temp_list=[
                                'bandId'=>$h['bandId'],
                                'description'=>$age_list[$h['bandId']]['description'],
                                'age'=>$age_list[$h['bandId']]['age'],
                                'price'=>$h['prices'][0]['price'],
                                'merchantNetPrice'=>$merchantNetPrice*1.05,//增加5%的税
                                'max'=>isset($h['maximumCountRequired'])?$h['maximumCountRequired']:9,
                                'min'=>isset($h['minimumCountRequired'])?$h['minimumCountRequired']:1,
                            ];
                            if(count($h['prices'])>1){
                                $temp_list['otherprice']=count($h['prices']);
                            }
                            $temp_price[]=$temp_list;
                        }
                    }
                    //从temp_price中获取最大人数 最小人数 最大价格
                    $peo_max=[]; $peo_min=[];$price_max=[];$m_price_max=[];  //需要判断参数
                    foreach ($temp_price as $price){
                        $peo_max[]=$price['max'];
                        $peo_min[]=$price['min'];
                        $price_max[]=$price['price'];
                        $m_price_max[]=$price['merchantNetPrice'];
                    }
                    $temp_end=[
                        'bandId'=>$temp_price[0]['bandId'],
                        'description'=>$temp_price[0]['description'],
                        'age'=>$temp_price[0]['age'],
                        'price'=>max($price_max),
                        'merchantNetPrice'=>max($m_price_max),
                        'max'=>max($peo_max),
                        'min'=>min($peo_min),
                    ];
                    $temp['ageBands'][]=$temp_end;
                    $res_list[$j['gradeCode']][]=$temp;
                }else{
                    foreach ($j['pricingMatrix'] as $l){ //bookingDate
                        $temp=[
                            'bookingDate'=>$l['bookingDate'],
                            'ageBands'=>[]
                        ];
                        foreach ($l['ageBandPrices'] as $h){ //bandId min max
                            $temp_list=[
                                'bandId'=>$h['bandId'],
                                'description'=>$age_list[$h['bandId']]['description'],
                                'age'=>$age_list[$h['bandId']]['age'],
                                'price'=>$h['prices'][0]['price'],
                                'merchantNetPrice'=>$h['prices'][0]['merchantNetPrice']*1.05,//增加5%的税
                                'max'=>isset($h['maximumCountRequired'])?$h['maximumCountRequired']:9,
                                'min'=>isset($h['minimumCountRequired'])?$h['minimumCountRequired']:1,
                            ];
                            if(count($h['prices'])>1){
                                $temp_list['otherprice']=0;
                            }
                            $temp['ageBands'][]=$temp_list;
                        }
                        $res_list[$j['gradeCode']][]=$temp;
                    }
                }
            }
        }
        if($code_err){
            $file = 'log.txt';
            file_put_contents($file, ' 异常code：'.$code.PHP_EOL, FILE_APPEND);
        }
        return $res_list;
    }

    /*
     * 订单：预计价格,重新计算价格触发定价规则
     * /service/booking/calculateprice
     * status :true 为获取单件价格
     */
    public function calculatePrice($code='3425CBDINNER', $time='2018-10-02', $tourGradeCode='PM1900',$bandid=['1','2','3'],$status=true)
    {
        $currencyCode=$this->currencyCode;
        $url = $this->url.'/service/booking/calculateprice';
        $list=[
//            'promoCode'=>null, //折扣或其他目的创建促销代码
//            'partnerDetail'=>null,
            'currencyCode'=>$currencyCode,  //美元
            'items'=>[
                [
//                    'specialReservation'=>false,
                    'travelDate'=>$time,
                    'productCode'=>$code,
                    'tourGradeCode'=> $tourGradeCode,
                    'travellers'=>[]
                ]
            ]
        ];
        if($status){
            $redata=[];
            foreach ($bandid as $k){
                $list['items'][0]['travellers'][0]['bandId']=$k;
//                dump($list);
                $data=$this->post_curl($url,json_encode($list));
                $data=$this->object_array($data)['data'];
//                dump($data);
                $redata[$k]=$data['itinerary']['totalPriceFormatted'];
            }
//            dump($redata);
            return $redata;
        }else{
            foreach ($bandid as $k){
                $arr=[];
                $arr=[
                    'bandId'=>$k,
                ];
                $list['items'][0]['travellers'][]=$arr;
            }
            $data=$this->post_curl($url,json_encode($list),[$this->en_header]);
            $data=$this->object_array($data)['data']['itinerary']['totalPriceFormatted'];
//            dump($data);
            return $data;
        }
    }

    /*
     * 订单： 状态查询
     */
    public function bookstatus(){

        $list=[
            'bookingDateFrom'=>'2018-09-12',
            'bookingDateTo'=>'2018-10-24',
            'itineraryIds'=>'',
            'itemIds'=>'',
            'distributorRefs'=>'',
            'distributorItemRefs'=>'',
            'leadFirstName'=>'',
            'leadSurname'=>'',
        ];
//        $list=array_filter($list);
        $url = $this->url.'/service/booking/status';
        dump($list);
        $data=$this->post_curl($url,json_encode($list),[$this->en_header]);
//        $data=$this->object_array($data);
        dump($data);
    }

    /*
     * 订单：viator订单查询
     */
    public function viatorOrder($email='',$itineraryId=''){
        $url = $this->url.'/service/booking/mybookings';

        $url=$url.'&email='.$email.'&itineraryOrItemId='.$itineraryId;
        $res_data=$this->get_curl($url,[$this->en_header]);
        $res=$this->object_array($res_data)['data'][0];
        $status = 1;
        // 返回 1 状态待确认 2 确认完成，下单失败  3确认完成，下单成功
        if($res['bookingStatus']['confirmed']==true){
            $status = 3;
        }
        if($res['bookingStatus']['pending']==true){
            $status = 1;
        }
        if($res['bookingStatus']['failed']==true){
            $status = 2;
        }

        return array('status'=>$status,'res'=>$res_data);
    }

    /*
     * 订单：凭证获取
     */
    public function getVoucher($id=''){
        $voucherKey=Db::name('order_byviator')->where('id',$id)->field('voucherKey')->find()['voucherKey'];
        if(empty($voucherKey)){
            return '获取凭证失败';
        }
        $url = $this->url.'/service/booking/voucher?voucherKey='.$voucherKey;
        $data=$this->get_curl($url,[$this->en_header]);
        $data=$this->object_array($data);
        if($data['errorMessageText']==NULL){
            return $data['data'];
        }else{
            return '获取凭证失败';
        }
    }

    /*
   * 翻译api  有道智云
   */
    public function etoc($str='Singapore',$from='auto',$to='auto'){
        $url='http://openapi.youdao.com/api';
        $appKey='65fc32d43c2bcff2';
        $key='M5Y5QUlIEy2OmccRfejHhKYXgwXQaWbX';
        $list['q']=urlencode($str);
        $from=urlencode($from);
        $to=urlencode($to);
        $appKey=urlencode($appKey);
        $num=rand(1,99);
        $sign=$appKey.$str.$num.$key;
        $list['sign']=urlencode(md5($sign));
        $url=$url.'?q='.$list['q'].'&from='.$from.'&to='.$to.'&appKey='.$appKey.'&salt='.$num.'&sign='.$list['sign'];
        $res=$this->get_curl($url);
        return isset($res['translation'][0])?$res['translation'][0]:null;
    }

    /*
    * 翻译api  腾讯云
     *  Action ID:TextTranslate
     * SecretId:AKIDa5QbaOOa8Vp4C97Y4WnurdEoDTZU60Ws
     * SecretKey:vgHhvyugHk8LNJ6jBZnqiOtENLArNjw0
     * APPID:1257355942
     * Region:ap-chongqing  区域参数(必选：否)
     * 以上为控制台固定参数
     *
     * Signature 签名
     * Nonce  随机正整数
     * Timestamp 时间戳
     *
     * 接口参数
     * ProjectId ： 项目 ID
     * Source ： 源语言
     * SourceText ： 待翻译的文本
     * Target ： 目标语言
     * /v2/index.php
    */
    public function etocTencent($str='Singapore',$from='en',$to='zh',$redata='true'){
        $url="https://tmt.ap-chongqing.tencentcloudapi.com/?";
        $time=time();
        $num=rand(1,99);
        //公共函数
        $list=[
            'Action'=>'TextTranslate',
            'Region'=>'ap-chongqing',
            'Timestamp'=>$time,
            'Nonce'=>$num,
            'SecretId'=>'AKIDa5QbaOOa8Vp4C97Y4WnurdEoDTZU60Ws',
            'Version'=> '2018-03-21',
            "SignatureMethod" => "HmacSHA256",
        ];

        $list['ProjectId']=0;
        $list['Source']=$from;
        $list['SourceText']=$str;
        $list['Target']=$to;
        //生成签名
        $list['Signature']=$this->tencentToken($list,'tmt.ap-chongqing.tencentcloudapi.com/','GET','vgHhvyugHk8LNJ6jBZnqiOtENLArNjw0');

//        dump($list);
        //生成url
        $arr=[];
        foreach ($list as $k=>$v){
//            $arr[]=$k.'='.$v;
            $arr[]=$k.'='.urlencode($v);
        }
        $arr=implode('&',$arr);
        $url=$url.$arr;
//        dump($url);
        $data=$this->get_curl($url);
        if($redata){
            return $data['Response']['TargetText'];
        }else{
            return $data;
        }
    }

    /*
     * 鉴权 ： 腾讯云
     * arr : 参数组
     * url : 主机和路径
     * type : 请求类型 大写
     *
     */
    public function tencentToken($arr,$url,$type,$secretKey){
        ksort($arr);
        $list=[];
        foreach ($arr as $k=>$v){
            $list[]=$k.'='.$v;
        }
        $arr=implode('&',$list);
        $oldstr=$type.$url.'?'.$arr;
        $signStr = base64_encode(hash_hmac('sha256', $oldstr, $secretKey, true));
        return $signStr;
    }

    /*
     *  数据整理,数组转字符串(日诶 我在想什么 有函数不用，算了懒得改)
     */
    public function arrToStr($arr){
        if (!is_array($arr)){
            return $arr;
        }
        $inclusions='';
        foreach ($arr as $a){
            if(empty($inclusions)){
                $inclusions=$a.';';
            }else{
                $inclusions=$inclusions.$a.';';
            }
        }
        return $inclusions;
    }

    /*
     * 递归排序
     */
    public function arrKsort($arr){
        foreach ($arr as $iu=>$a){
            if (is_array($a)){
                $arr[$iu]=$this->arrKsort($a);
            }
        }
        ksort($arr);
        return $arr;
    }

    /*
     * 获取套餐类型
     */
    public function getGrend($code='',$data=''){
        if(empty($data)){
            $data=$this->goodsDetail($code,'tourGrades');
        }
        $specs=[];
        foreach ($data as $d){
            $arr=[];
            $arr['code']=$code;
            $arr['specs_ename']=empty($d['gradeTitle'])?'default':$d['gradeTitle'];
            $arr['specs_name']=empty($d['gradeTitle'])?'普通套餐':$this->etocTencent($d['gradeTitle']);
            $arr['gradeCode']=$d['gradeCode'];
            $arr['specs_id']=9999999999;
            $arr['specs_types']=1;
            $specs[]=$arr;
        }
        return $specs;
    }

    /*
     * 用于三方商品状态判断
     * 追加每日日志
     */
    public function checkGoods($code){
        $path='./log'; //文件嫁生成
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $logFile='./log/'.date('Ymd').'txt'; //日志地址
        $writeData[]=date('H:i;s').'时进行状态判断，code为：'.$code;

        $res=$this->goodsDetail($code);

        //为增加预约问题数据做  wap/goods/details
        $Final_return_arr = [];//最终返回数组    code=1失败，code=0为正常

        $writeData[]='$res的长度为'.count($res);
        if(empty($res)){
            Db::name('goods')->where('code',$code)->where('show','2')->update(['goods_status'=>2,'accidentDrop'=>1]);
            $rearr=[
                'code'=>1,
                'msg'=>'商品已下架'
            ];
            $writeData[]='msg错误为:商品已下架';
            $this->setFiles($writeData,$logFile);

            $Final_return_arr['code'] = 1;
            $Final_return_arr['data'] = $rearr;
            return $Final_return_arr;
        }
        $resArray1=cache($code.'price');
        $writeData[]='$resArray1的长度为'.count($resArray1);
        if(empty($resArray1)){
            Db::name('goods')->where('code',$code)->where('show','2')->update(['goods_status'=>2,'accidentDrop'=>1]);
            $rearr=[
                'code'=>1,
                'msg'=>'未能获取商品价格，商品已下架'
            ];

            $writeData[]='msg错误为:未能获取商品价格';
            $this->setFiles($writeData,$logFile);

            $Final_return_arr['code'] = 1;
            $Final_return_arr['data'] = $rearr;
            return $Final_return_arr;
        }else{
            $endtime=[];
            foreach ($resArray1 as $a){
                $endtime[]=strtotime($a[0]['bookingDate']);
            }
            $endtime=min($endtime);
            $nexttime=strtotime('+1 month');
            $lasttime=strtotime(date('Y-m-t 23:00:00',$nexttime));
            $writeData[]='$endtime的值为'.$endtime.'.$lasttime的值为'.$lasttime;
            if($endtime>$lasttime){
                Db::name('goods')->where('code',$code)->update(['goods_status'=>2,'accidentDrop'=>1]);
                $rearr=[
                    'code'=>1,
                    'msg'=>'预定时间不足一周，商品已下架'
                ];

                $writeData[]='预约时间不足';
                $this->setFiles($writeData,$logFile);

                $Final_return_arr['code'] = 1;
                $Final_return_arr['data'] = $rearr;
                return $Final_return_arr;
            }
        }

        $Final_return_arr['code'] = 0;//0为正常
        $Final_return_arr['data'] = $res;
        return $Final_return_arr;
    }

    //重新查询被标记意外下架的商品
    public function secondTimePrice(){
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//让程序一直执行下去
        $timing=true;//结束条件
        //所有待获取的商品
        $where['accidentDrop'] = 1;//标记为意外下架
        $where['goods_status'] = 1;//售卖中
        $where['show'] = 2;//第三方的
        $this->writeLog("【secondTimePrice】开始更新价格");
        $goodsList = Db::name('goods')->where($where)->field('code')->select();
        if (empty($goodsList)) {
            $this->writeLog("【secondTimePrice】抓取结束，无更新");
            die;
        }
        //查询六个月
        $month=date('m');
        $lastMonth=date('m',strtotime('+1 month'));
        $lastMonth_3=date('m',strtotime('+2 month'));
        $lastMonth_4=date('m',strtotime('+3 month'));
        $lastMonth_5=date('m',strtotime('+4 month'));
        $lastMonth_6=date('m',strtotime('+5 month'));
        do{
            if (empty($goodsList)) $timing=false;  //终止条件
            //获取code和商品信息
            $code=array_pop($goodsList)['code'];  //当前商品
            $goodsdetail=$this->goodsDetail($code);
            if(empty($goodsdetail)){
                 //发送邮件给小美 20200202 增加邮件提醒人张梦雄（chris@kuaibangxing.com）
                $goods = Db::name('goods')->where('code',$code)->field("goods_name")->find();
                $title = "【".$goods['goods_name']."】商品被自动下架了，请速查看！";
                $content = "下架商品编号：".$code."。 下架原因：取不到goodsDetail数据";
                $msg=new Msg();
                $msg->kbxemailcode($title,$content,'david@kuaibangxing.com,chris@kuaibangxing.com');
                $updateArr['goods_status'] = 2;
                //商品下架
                Db::name('goods')->where('code',$code)->where('show','2')->update($updateArr);

                //执行标品下架
                $standard = db("standard")
                    ->alias("s")
                    ->join("goods g","s.goods_id=g.goods_id","left")
                    ->where("g.code",$code)
                    ->field("s.id")
                    ->find();
                if(!empty($standard)){
                    db("standard")->where('id',$standard['id'])->update(['show_toB'=>0]);
                }

                continue;
            }
            //获取价格 3902LANDSEA3
            $resArray1=$this->getPriceShow($code,$month,$goodsdetail['ageBands']);
            $resArray2=$this->getPriceShow($code,$lastMonth,$goodsdetail['ageBands']);
            $resArray3=$this->getPriceShow($code,$lastMonth_3,$goodsdetail['ageBands']);
            $resArray4=$this->getPriceShow($code,$lastMonth_4,$goodsdetail['ageBands']);
            $resArray5=$this->getPriceShow($code,$lastMonth_5,$goodsdetail['ageBands']);
            $resArray6=$this->getPriceShow($code,$lastMonth_6,$goodsdetail['ageBands']);
            if(empty($resArray1)){
                $res_arr = array();
                if(!empty($resArray2)){
                    $resArray1=$resArray2;
                    $res_arr = array($resArray3,$resArray4,$resArray5,$resArray6);
                }else{
                    if(!empty($resArray3)){
                        $resArray1=$resArray3;
                        $res_arr = array($resArray4,$resArray5,$resArray6);
                    }else{
                        if(!empty($resArray4)){
                            $resArray1=$resArray4;
                            $res_arr = array($resArray5,$resArray6);
                        }else{
                            if(!empty($resArray5)){
                                $resArray1=$resArray5;
                                $res_arr = array($resArray6);
                            }else{
                                if(!empty($resArray6)){
                                    $resArray1=$resArray6;
                                }
                            }
                        }
                    }
                }
            }else{
                $res_arr = array($resArray2,$resArray3,$resArray4,$resArray5,$resArray6);
            }
            foreach ($res_arr as $res_v) {
                if(!empty($res_v)){
                    foreach ($res_v as $a=>$d){
                        if(!isset($resArray1[$a])){
                            $resArray1[$a]=[];
                        }
                        foreach ($d as $k){
                            array_push($resArray1[$a],$k);
                        }
                    }
                }
            }
            if(is_array($resArray1)){
                $resArray1=array_filter($resArray1);
            }else{
                $resArray1='';
            }
            //补充 如果六个月内没有价格 则商品下架
            if(empty($resArray1)){
                //发送邮件给小美 20200202 增加邮件提醒人张梦雄（chris@kuaibangxing.com）
                $goods = Db::name('goods')->where('code',$code)->field("goods_name")->find();
                $title = "【".$goods['goods_name']."】商品被自动下架了，请速查看！";
                $content = "下架商品编号：".$code."。 下架原因：六个月内没有价格";
                $msg=new Msg();
                $msg->kbxemailcode($title,$content,'david@kuaibangxing.com,chris@kuaibangxing.com');
                $updateArr['goods_status'] = 2;
                Db::name('goods')->where('code',$code)->where('show','2')->update($updateArr);

                //执行标品下架
                $standard = db("standard")
                    ->alias("s")
                    ->join("goods g","s.goods_id=g.goods_id","left")
                    ->where("g.code",$code)
                    ->field("s.id")
                    ->find();
                if(!empty($standard)){
                    db("standard")->where('id',$standard['id'])->update(['show_toB'=>0]);
                }

                continue;
            }else{
                $endtime=[];
                foreach ($resArray1 as $a){
                    $endtime[]=strtotime($a[0]['bookingDate']);
                }
                $endtime=min($endtime);
                $nexttime=strtotime('+5 month');
                $lasttime=strtotime(date('Y-m-t 23:00:00',$nexttime));
                if($endtime>$lasttime){
                    //发送邮件给小美 20200202 增加邮件提醒人张梦雄（chris@kuaibangxing.com）
                    $goods = Db::name('goods')->where('code',$code)->field("goods_name")->find();
                    $title = "【".$goods['goods_name']."】商品被自动下架了，请速查看！";
                    $content = "下架商品编号：".$code."。 下架原因：预定日期在六个月以后";
                    $msg=new Msg();
                    $msg->kbxemailcode($title,$content,'david@kuaibangxing.com,chris@kuaibangxing.com');
                    $updateArr['goods_status'] = 2;
                    Db::name('goods')->where('code',$code)->where('show','2')->update($updateArr);
                    continue;
                }
            }
            //获取套餐分类
            $tourGrades=$this->getGrend($code,$goodsdetail['tourGrades']);
            //将没有价格的分类去掉
            $temp_key=[];
            foreach ($resArray1 as $res_key=>$res_val){
                $temp_key[]=$res_key;
            }
            foreach ($tourGrades as $grade_key=>$grade){
                if(!in_array($grade['gradeCode'],$temp_key)){
                    unset($tourGrades[$grade_key]);
                }
            }
            $resArray1["month_num"] = 6;
            //价格缓存
            cache($code.'price',$resArray1);
            //套餐类型缓存
            cache($code.'type',$tourGrades);
            //取消意外下架标记
            Db::name('goods')->where('code',$code)->where('show','2')->update(['accidentDrop'=>0]);
            //数据库写入记录
            $time=date('Y-m-d H:i:s');
            $res=Db::name('goods_price')->where('code',$code)->find();
            if($res){
                Db::name('goods_price')->where('code',$code)->update(['time'=>$time]);
            }else{
                $data=[
                    'code'=>$code,
                    'time'=>$time
                ];
                Db::name('goods_price')->insert($data);
            }
            //强行终止
            $goonStatus=Db::name('goods_price')->where('id',1)->find()['time'];
            if($goonStatus=='1'){
                $timing=false;
            }
        }while($timing);
        $this->writeLog("【secondTimePrice】抓取结束");
        dump('抓取结束');
    }

    /*
     * 自定义日志
     */
    public function setFiles($files,$path){
        if(is_array($files)){
            foreach ($files as $file){
                file_put_contents($path,$file.PHP_EOL,FILE_APPEND);
            }
        }else{
            file_put_contents($path,$files.PHP_EOL,FILE_APPEND);
        }

        return true;
    }

    /*
     * 删除：因接口调试出现重复数据
     */
    public function delcopy(){
        exit;
        $data=Db::query("SELECT * FROM (SELECT COUNT(*) as num,code FROM tplay_goods GROUP BY `code`) as a WHERE num>1");
        foreach ($data as $a){
            if(!empty($a['code'])){
                dump($a['code']);
                $res=Db::name('goods')->where('code',$a['code'])->field('goods_id')->find();
                Db::name('goods')->where('goods_id','NEQ',$res['goods_id'])->where('code',$a['code'])->delete();
            }
        }
        dump('结束');
    }

    //查询Viator订单
    public function getMyOrder()
    {
        $order_no=input('order_no');
        $url = $this->url.'/service/booking/mybookings';
        $where['order_no'] = $order_no;
        $data=Db::name('order_byviator')->where($where)->field('id,email,itineraryId')->find();

        $url=$url.'&email='.$data['email'].'&itineraryOrItemId='.$data['itineraryId'];
        $res=$this->get_curl($url,[$this->en_header]);
        $res=$this->object_array($res);

        echo "<pre>";
        var_dump($res);
        echo "</pre>";
    }

    //比较高低价，查看是否有变化
    public function comparePrice($code,$dateArr){
        $priceArr = [];
        foreach ($dateArr as $datekey=>$datevalue) {
            foreach ($datevalue as $key=>$value) {
                if(!empty($value['ageBands'])){
                    foreach ($value['ageBands'] as $k=>$v) {
                        if($v['bandId']==1){
                            $priceArr[] = $v['price'];
                        }
                    }
                }
            }
        }

        $resData = '';
        if(!empty($priceArr)){
            $maxPrive = max($priceArr);
            $minPrive = min($priceArr);
            $resData = $minPrive."_".$maxPrive;
        }

        $flag = 0;//为1时价格有变动，需要发送邮件提醒
        $cachePriceData = cache($code.'limit');
        if(empty($cachePriceData) || $cachePriceData==''){
            if(!empty($resData)){
                cache($code.'limit',$resData);
            }
            return true;
        }else{
            if($cachePriceData!==$resData){
                $flag = 1;
            }
        }

        if($flag==1){//发邮件提醒
            $cachePriceStr = !empty($cachePriceData) ? $cachePriceData : '';
            $resStr = !empty($resData) ? $resData : '';
            $goods = db("goods")->where("code",$code)->field("goods_id,goods_name")->find();
            $title = "【".$goods['goods_name']."】商品有价格变动，请速查看！";
            $content = "商品ID：".$goods['goods_id']."，商品code：".$code."<br>之前成人票价格区间：".$cachePriceStr."；<br>现在成人票价格区间：".$resStr;
            $msg = new Msg();
            $msg->kbxemailcode($title,$content,'david@kuaibangxing.com');
        }

        if(!empty($resData)){
            cache($code.'limit',$resData);
        }else{
            cache($code.'limit',null);
        }

        return true;
    }


    public function getPriceShow111($code='6997CITY',$month='10',$ageBands=''){
        $month=empty($month)?date('m'):$month;
        $url = $this->url . '/service/booking/availability/tourgrades/pricingmatrix';
        $currencyCode=$this->currencyCode;
        $month_1=date('m');
        $year=date('Y');
        if($month<$month_1){
            $year=$year+1;
        }
        $list=[
            'productCode'=>$code,
            'month'=>$month,
            'year'=>$year,
            'currencyCode'=>$currencyCode
        ];
        $data=$this->post_curl($url,json_encode($list),[$this->en_header]);
        $data=$this->object_array($data);

        if(empty($data['data'])){
            return '';
        }
        //年龄组
        $age_list=[];
        if(empty($ageBands)){
            $ageBands=$this->goodsDetail($code,'ageBands');
        }
        foreach ($ageBands as $w){
            $age_list[$w['bandId']]['description']=$w['description'];
            $age_list[$w['bandId']]['age']=$w['ageFrom'].'-'.$w['ageTo'];
        }

        //取出有价格的日期
        $data=$data['data']['dates'];

        $res_list=[];//返回的数据
        $code_err=false;

        if(!is_array($data)) return '';


        echo "<pre>";
        var_dump($data);
        echo "</pre>";
        exit;



        foreach ($data as $k){
            foreach ($k['tourGrades'] as $j){  //gradeCode
                //由于对于返回结果不明确 记录异常商品
                if(count($j['pricingMatrix'])>1){
                    $code_err=true;
                    $temp_price=[];
                    foreach ($j['pricingMatrix'] as $l){ //bookingDate
                        $temp=[
                            'bookingDate'=>$l['bookingDate'],
                            'ageBands'=>[]
                        ];
                        foreach ($l['ageBandPrices'] as $h){ //bandId min max
                            $merchantNetPrice = $h['prices'][0]['merchantNetPrice'];
                            $temp_list=[
                                'bandId'=>$h['bandId'],
                                'description'=>$age_list[$h['bandId']]['description'],
                                'age'=>$age_list[$h['bandId']]['age'],
                                'price'=>$h['prices'][0]['price'],
                                'merchantNetPrice'=>$merchantNetPrice*1.05,//增加5%的税
                                'max'=>isset($h['maximumCountRequired'])?$h['maximumCountRequired']:9,
                                'min'=>isset($h['minimumCountRequired'])?$h['minimumCountRequired']:1,
                            ];
                            if(count($h['prices'])>1){
                                $temp_list['otherprice']=count($h['prices']);
                            }
                            $temp_price[]=$temp_list;
                        }
                    }
                    //从temp_price中获取最大人数 最小人数 最大价格
                    $peo_max=[]; $peo_min=[];$price_max=[];$m_price_max=[];  //需要判断参数
                    foreach ($temp_price as $price){
                        $peo_max[]=$price['max'];
                        $peo_min[]=$price['min'];
                        $price_max[]=$price['price'];
                        $m_price_max[]=$price['merchantNetPrice'];
                    }
                    $temp_end=[
                        'bandId'=>$temp_price[0]['bandId'],
                        'description'=>$temp_price[0]['description'],
                        'age'=>$temp_price[0]['age'],
                        'price'=>max($price_max),
                        'merchantNetPrice'=>max($m_price_max),
                        'max'=>max($peo_max),
                        'min'=>min($peo_min),
                    ];
                    $temp['ageBands'][]=$temp_end;
                    $res_list[$j['gradeCode']][]=$temp;
                }else{
                    foreach ($j['pricingMatrix'] as $l){ //bookingDate
                        $temp=[
                            'bookingDate'=>$l['bookingDate'],
                            'ageBands'=>[]
                        ];
                        foreach ($l['ageBandPrices'] as $h){ //bandId min max
                            $temp_list=[
                                'bandId'=>$h['bandId'],
                                'description'=>$age_list[$h['bandId']]['description'],
                                'age'=>$age_list[$h['bandId']]['age'],
                                'price'=>$h['prices'][0]['price'],
                                'merchantNetPrice'=>$h['prices'][0]['merchantNetPrice']*1.05,//增加5%的税
                                'max'=>isset($h['maximumCountRequired'])?$h['maximumCountRequired']:9,
                                'min'=>isset($h['minimumCountRequired'])?$h['minimumCountRequired']:1,
                            ];
                            if(count($h['prices'])>1){
                                $temp_list['otherprice']=0;
                            }
                            $temp['ageBands'][]=$temp_list;
                        }
                        $res_list[$j['gradeCode']][]=$temp;
                    }
                }
            }
        }

        echo "<pre>";
        var_dump($res_list);
        echo "</pre>";
        exit;
    }

    //手动抓取城市viator商品数据
    public function getViatorGoodsByCity($city_id=52){
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//让程序一直执行下去
        //限制每两小时只能执行一次
        $isRunning = Cache::get('getViatorGoodsByCity');
        if(empty($isRunning)){
            Cache::set('getViatorGoodsByCity',time() + 3600,3600);
        }else{
            $limit_time = $isRunning - time();
            if($limit_time > 60){
                $mintue = intval( $limit_time/60 );
                $second = $limit_time - $mintue * 60;
                $limit_time = $mintue.'分'.$second.'秒';
            }else{
                $limit_time .= '秒';
            }
            $msg = "限制1小时内只能执行一次，剩余" . $limit_time;
            $this->writeLog($msg);
            echo $msg;
            exit;
        }
        $this->writeLog("【开始抓取】城市ID为".$city_id."的viator商品");
        echo "抓取開始";
        echo "<br>";

        $url = $this->url . '/service/search/products';

        $citymsg = Db::name('city')->where('type','CITY')->where('id',$city_id)->where('getgoods','1')->find();
        if(empty($citymsg['destid'])){
            return false; //结束
        }
        //抓取一年内的商品
        $list['startDate'] = date('Y-m-d');
        $list['endDate'] = date("Y-m-d",strtotime("+1 year",time()));
        $list['destId'] = $citymsg['destid'];
        $list['currencyCode'] = $this->currencyCode;
        //**********************************************
        //先查询中文页，再取英文页补全
        //by suley
        //现有数据库code集
        $code_list = Db::name('goods')->where('city_id',$citymsg['id'])->where('show','2')->column('code');
        $code_list = empty($code_list)?[]:$code_list;

        db::startTrans();
        try{
            $api_arr = array("zh"=>$this->zh_header,"en"=>$this->en_header);
            foreach ($api_arr as $k_api_key=>$v_api_key){
                $data = (array)$this->post_curl($url,json_encode($list),[$v_api_key]);
                $data = $this->object_array($data);
                //去除数据库已存在的商品
                echo "一共存在".count($data['data'])."个商品<br>";
                $this->writeLog("【一共存在】".count($data['data'])."个商品");
                //去除已入库的viator商品
                foreach ($data['data'] as $k=>$a){
                    if(in_array($a['code'],$code_list)){
                        unset($data['data'][$k]);
                    }else{
                        $code_list[] = $a['code'];
                    }
                }
                echo "本次新增".count($data['data'])."个商品<br>";
                $this->writeLog("【本次新增】".count($data['data'])."个商品");
                if(!empty($data['data'])){
                    $api_key = $k_api_key=='zh' ? 1 : 0;
                    $res = $this->setGoods($data['data'],$citymsg['id'],$citymsg['destid'],$api_key);
                    //中英文Apikey区分标识
                    if($k_api_key=='zh'){
                        echo "中文key:【ID".$citymsg['id']."城市】新增商品".count($res)."件<br>";
                        $this->writeLog("中文key:【ID".$citymsg['id']."城市】新增商品".count($res)."件");
                    }else{
                        echo "英文key:【ID".$citymsg['id']."城市】新增商品".count($res)."件<br>";
                        $this->writeLog("英文key:【ID".$citymsg['id']."城市】新增商品".count($res)."件");
                    }
                    $arrlist = array_chunk($res,50);
                    foreach ($arrlist as $a){
                        Db::name('goods')->insertAll($a);
                    }
                }
            }
            Db::name('city')->where('id',$citymsg['id'])->update(['updating'=>time()]);
            $this->writeLog("【抓取完毕】城市".$city_id."的viator商品");
            echo "抓取完成";
            db::commit();
        }catch(Exception $e){
            db::rollback();
            $this->writeLog("遇到错误：".$e->getMessage());
            echo "遇到错误：".$e->getMessage();
        }
        //请求完毕主动释放缓存锁
        Cache::rm('getViatorGoodsByCity');
        exit;
    }

    //测试 查看viatorGoodsList
    public function showViatorGoodsListByCity($city_id=52)
    {
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//让程序一直执行下去

        $url = $this->url . '/service/search/products';

        $citymsg = Db::name('city')->where('type','CITY')->where('id',$city_id)->where('getgoods','1')->find();
        if(empty($citymsg['destid'])){
            return false; //结束
        }
        //抓取一年内的商品
        $list['startDate'] = date('Y-m-d');
        $list['endDate'] = date("Y-m-d",strtotime("+1 year",time()));
        $list['destId'] = $citymsg['destid'];
        $list['currencyCode'] = $this->currencyCode;

        $api_arr = array("zh"=>$this->zh_header,"en"=>$this->en_header);
        //现有数据库code集
        $code_list = db('goods')->where('city_id',$citymsg['id'])->where('show','2')->column('code');
        $code_list = empty($code_list)?[]:$code_list;
        $this->writeLog("开始更新数据...");
        $result = [];
        foreach ($api_arr as $k_api_key=>$v_api_key) {
            $api_key = $k_api_key=='zh' ? 1 : 0;
            $data = (array)$this->post_curl($url, json_encode($list), [$v_api_key]);
            $data = $this->object_array($data);
            if(!empty($data['data'])){
                //去除已入库的viator商品
                foreach ($data['data'] as $k=>$a){
                    if(in_array($a['code'],$code_list)){
                        unset($data['data'][$k]);
                    }else{
                        $this->writeLog("新商品code：".$a['code']);
                        $code_list[] = $a['code'];
                    }
                }
                if(!empty($data['data'])){
                    foreach ($data['data'] as $k=>$a){
                        $res = $this->setGoods($data['data'],$citymsg['id'],$citymsg['destid'],$api_key);
                        if(!empty($res)){
                            $this->writeLog("新入库商品code：".json_encode(array_column($res,'code')));
                            $result = array_merge($result,$res);
                        }
                    }
                }
            }
        }
        $this->writeLog('获取未入库viator数据,共【'.count($result).'】');
        $this->writeLog("更新数据结束");
        return json_encode($result);

    }
    //20210423获取viator商品的多张图片拼接数据
    public function getViatorBannerImages($images=[],$img_field='photoURL',$default_img='')
    {
        if(empty($images)) return $default_img;
        $images = array_slice($images,0,15);
        return implode(',',array_column($images,$img_field));
    }

    //手动拉去viator最新详情信息
    public function pullViatorImages(Request $request)
    {
        //获取产品的code
        if(!$request->isPost()) return json(['code'=>0,'msg'=>'请以POST方式请求！']);
        $code = $request->post('code','');
        if(empty($code)) return json(['code'=>0,'msg'=>'缺少viatorCode！']);
        //检查是否入库
        $existViatorData = db('goods')->where(['show'=>2,'code'=>$code])->find();

        if(empty($existViatorData)) return json(['code'=>0,'msg'=>'暂未查询到相关viator商品！']);

        //拉取viator远程图片数据
        $remoteViatorImages = $this->goodsDetail($code,'productPhotos',true);
        $remoteViatorImages = array_column($remoteViatorImages,'photoURL');
        if(!empty($remoteViatorImages)){
            return json(['code'=>200,'msg'=>'success','data'=>$remoteViatorImages]);
        }else{
            return json(['code'=>0,'msg'=>'暂无数据','data'=>[]]);
        }

    }

    public function pullVitorImageByViatorCodes($viatorGoods=[],$viator_field='code')
    {
        db::startTrans();
        try{
            foreach ($viatorGoods as $key=>$value){
                $remoteViatorImages = $this->goodsDetail($value[$viator_field],'productPhotos',true);
                $remoteViatorImages = array_column($remoteViatorImages,'photoURL');
                $goods_images_arr = array_filter(explode(',',$value['goods_image']));
                $goods_images_arr = array_merge($goods_images_arr,$remoteViatorImages);
                $goods_images = empty($goods_images_arr)?'':implode(',',$goods_images_arr);
                db('goods')->where(['show'=>2,'code'=>$value[$viator_field]])->update([
                    'goods_image'=>$goods_images,
                    'small_image'=>$goods_images
                ]);
                $viatorGoods[$key]['goods_image'] = $goods_images_arr;
                $viatorGoods[$key]['countImage'] = count($goods_images_arr);
                $viatorGoods[$key]['countNewImage'] = count($remoteViatorImages);
                $this->writeLog("viator商品【".$value[$viator_field]."】手动拉取更新图片".count($remoteViatorImages)."张");
            }
            db::commit();
            return $viatorGoods;
        }catch (\Exception $e){
            db::rollback();
            return $e->getMessage();
        }
    }

}